﻿//  Copyright (c) 2009 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System.Collections.Generic;
using System.Web.Mvc;

namespace DNA.Mvc
{
    /// <summary>
    /// Provides SiteMap control extension methods
    /// </summary>
    public static class SiteMapExtensions
    {
        //private static DynamicPageService Service { get { return WebSite.GetService<DynamicPageService>("pages"); } }

        /// <summary>
        /// Render the site map path html
        /// </summary>
        /// <param name="helper">The helper object</param>
        /// <returns>html of site map path</returns>
        public static MvcHtmlString SiteMapPath(this DnaControlFactory factory, IHierarchicalNodeProvider provider)
        {
            var builder = new NodeUIBuilder();

            var current = provider.CurrentNode;
            if (current != null)
            {
                var currentPage =(WebPage)current.Item;
                if (currentPage != null)
                {
                    if (currentPage.IsShared)
                    {
                        current.Title = WebSiteContext.Current.Title;
                    }
                }

                string icon = "ui-icon ui-icon-carat-1-e";
                //string nodeStyle = "float:left;margin-right:5px;";
                builder.WriteFullBeginTag("ul");

                List<HierarchicalNode> _array = new List<HierarchicalNode>();
                for (var node2 = current.ParentNode; node2 != null; node2 = node2.ParentNode)
                    _array.Add(node2);

                if (_array.Count > 0)
                    _array.Reverse();

                foreach (var node in _array)
                {
                    _RenderSiteMapNode(builder, node);
                    builder.WriteIconNode(icon);
                }
               // builder.WriteNode(current);
                _RenderSiteMapNode(builder, current);
                builder.WriteEndTag("ul");
            }
            return MvcHtmlString.Create(builder.ToString());
        }

        private static void _RenderSiteMapNode(NodeUIBuilder builder, HierarchicalNode node)
        {
            builder.WriteFullBeginTag("li");
            if (!string.IsNullOrEmpty(node.NavigateUrl))
                builder.WriteBeginLink(node);

            if (!string.IsNullOrEmpty(node.ImageUrl))
                builder.WriteImage(node, new { width = "16px", height = "16px" });

            builder.WriteTitle(node, null);

            if (!string.IsNullOrEmpty(node.NavigateUrl))
                builder.WriteEndTag("a");
            builder.WriteEndTag("li");
        }
    }
}
